package com.javen.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class VerifyMethod {

	public static final String NUMBRS_COUNT = "0123456789";

	public static void main(String[] args) {
		System.out.println(checkLetter("ABC"));
		System.out.println(turnTime("Thu May 07 14:33:19 CST 2015"));
		System.out.println(VerifyMethod.getStrTime(0));
		System.out.println(VerifyMethod.getPrintSize(136275));
		String str = "http://192.168.2.224:8080/#/mailbox?userId=20170614150911987227&activeCode=66755580907837362";
		String sert = "789,456";
		
		String[] tmpList = sert.split(",");
		for (int i = 0; i < tmpList.length; i++) {
			System.out.println("下标="+i+"，value："+tmpList[i].toString());
		}
		
	/*	String strTime = "2017-02-23 08:24:50.0";
		System.out.println("最多的时间"+VerifyMethod.getTimeData(strTime));
		String[] strTimeList =strTime.split("\\.");
		for (int i = 0; i < strTimeList.length; i++) {
			System.out.println(i+"下标："+ strTimeList[i].toString());
		}*/
		
		//System.out.println("时间"+VerifyMethod.get14Time(strTime));
		
		System.out.println(VerifyMethod.verifyHtmlUrl(str));
		System.out.println(getIp());
		String strCode = "15013528595";
		// System.out.println("服务器IP"+VerifyMethod.getServerIp());
		if (VerifyMethod.checkMobileNumber(strCode)) {
			System.out.println("是数字");
		} else {
			System.out.println("非数字");
		}
	}
	
/*	public static String getTimeData(String time){
		SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");     
		String date = sDateFormat.format(time);
		return date;  
	}*/
	
	public static String get14Time(String time){
		String[] strTimeList =time.split("\\.");
		return strTimeList[0];
	}
	
	/**
	 *是否为空
	 * @param s
	 * @return
	 */
	public static boolean checkDateNull(String s){
		if(s == null||s.equals("")){
			return false;
		}
		return true;
	}
	
	/**
	 * 是否是大写
	 * @param s
	 * @return
	 */
	public static boolean checkLetter(String s){
		for (int i = 0; i < s.length(); i++) {
	        char c = s.charAt(i);
	        if (!Character.isLowerCase(c)) {
	        	return true;
	        }
		}
		return false;
	}
	public static String turnTime(String time){
		String str="Thu May 07 14:33:19 CST 2015";
        String pattern = "EEE MMM dd HH:mm:ss zzz yyyy";   
        SimpleDateFormat df = new SimpleDateFormat(pattern,Locale.US);
        Date date;
		try {
			date = df.parse(str);
			SimpleDateFormat sdf2= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return sdf2.format(date);
		} catch (ParseException e1) {
			e1.printStackTrace();
		}   
		return null;
	}
	
	public static MsgResult getMsgResult(boolean result, String code, String message, Map<String,Object> params){
		MsgResult msgResultModel= new MsgResult();
		msgResultModel.setParams(params);
		msgResultModel.setResult(result);
		msgResultModel.setMessage(message);
		msgResultModel.setCode(code);
		return msgResultModel;
	}
	
	/**
	 * 生成图片long类型标识大小，转成B,KB,MB,GB,T
	 * @param size
	 * @return
	 */
	public static String getPrintSize(long size) {  
	    //如果字节数少于1024，则直接以B为单位，否则先除于1024，后3位因太少无意义  
	    if (size < 1024) {  
	        return String.valueOf(size) + "B";  
	    } else {  
	        size = size / 1024;  
	    }  
	    //如果原字节数除于1024之后，少于1024，则可以直接以KB作为单位  
	    //因为还没有到达要使用另一个单位的时候  
	    //接下去以此类推  
	    if (size < 1024) {  
	        return String.valueOf(size) + "KB";  
	    } else {  
	        size = size / 1024;  
	    }  
	    if (size < 1024) {  
	        //因为如果以MB为单位的话，要保留最后1位小数，  
	        //因此，把此数乘以100之后再取余  
	        size = size * 100;  
	        return String.valueOf((size / 100)) + "."  
	                + String.valueOf((size % 100)) + "MB";  
	    } else {  
	        //否则如果要以GB为单位的，先除于1024再作同样的处理  
	        size = size * 100 / 1024;  
	        return String.valueOf((size / 100)) + "."  
	                + String.valueOf((size % 100)) + "GB";  
	    }  
	}
	
	/**
	 * 转时间格式
	 * @param oldDateStr
	 * @return 返回yyyy-MM-dd格式字符串
	 * @throws ParseException
	 */
	public static String dealDateFormat(String oldDateStr){
		  //此格式只有  jdk 1.7才支持  yyyy-MM-dd'T'HH:mm:ss.SSSXXX          
		  DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");  //yyyy-MM-dd'T'HH:mm:ss.SSSZ
		  Date date = null;
		  Date date1 =null;
		try {
			date = df.parse(oldDateStr);
			SimpleDateFormat df1 = new SimpleDateFormat ("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
			date1= df1.parse(date.toString());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		  DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
		//  Date date3 =  df2.parse(date1.toString());
		  return df2.format(date1);
	}
	
	/**
	 * 校验是否是字母
	 * @param fstrData
	 * @return
	 */
	
	public static boolean checkAlphabet(String fstrData) {
		char c = fstrData.charAt(0);
		if (((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 拆除路径
	 * @param url
	 * @return
	 */
	public static Map<String, String> verifyHtmlUrl(String url) {
		if (!VerifyMethod.hasLength(url)) {
			return null;
		}

		if (url.indexOf("?") < 0) {
			System.err.println("url 不正确");
			return null;
		}

		String tmpUrl = url.substring(url.indexOf("?") + 1);
		// System.out.println(tmpUrl);
		String[] paramArr = tmpUrl.split("&");
		if (paramArr.length < 2) {
			System.err.println("url 不正确");
			return null;
		}

		Map<String, String> paramMap = new HashMap<String, String>();
		for (String param : paramArr) {
			System.out.println(param);
			String[] keyMapArr = param.split("=");
			if (keyMapArr.length < 1) {
				System.err.println("url 不正确");
				continue;
			}
			paramMap.put(keyMapArr[0], keyMapArr[1]);
			System.out.println(keyMapArr[0] + ":" + keyMapArr[1]);
		}

		if (paramMap.size() < 1) {
			return null;
		}
		for (String key : paramMap.keySet()) {
			System.out.println("map_" + key + ":" + paramMap.get(key));
		}

		/*
		 * String userId1=paramMap.get("userId"); String
		 * activeCode1=paramMap.get("activeCode");
		 */
		/*
		 * System.out.println("UserId="+userId1);
		 * System.out.println("activeCode="+activeCode1);
		 */
		return paramMap;

	}

	/**
	 * 判断是否为空
	 * 
	 * @param value
	 * @return
	 */
	public static Boolean hasLength(String value) {
		return value != null && !"".equals(value.trim());
	}

	/**
	 * 验证邮箱
	 * 
	 * @param email
	 * @return
	 */
	public static boolean checkEmail(String email) {
		boolean flag = false;
		try {
			String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
			Pattern regex = Pattern.compile(check);
			Matcher matcher = regex.matcher(email);
			flag = matcher.matches();
		} catch (Exception e) {
			flag = false;
		}
		return flag;
	}
	
	/**
	 * 获取HTTP://IP加项目名
	 * @param request
	 * @return
	 */
//	public static String checkHttpIp(HttpServletRequest request) {
//		StringBuffer url = request.getRequestURL();
//		return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getServletContext().getContextPath()).append("/").toString();
//	}

	/**
	 * 验证手机号码
	 * @param mobileNumber
	 * @return
	 */
	public static boolean checkMobileNumber(String mobileNumber) {
		boolean flag = false;
		try {
			Pattern regex = Pattern
					.compile("^(((1[4,5,3,8,7][0-9])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8})|(0\\d{2}-\\d{8})|(0\\d{3}-\\d{7})$");
			Matcher matcher = regex.matcher(mobileNumber);
			flag = matcher.matches();
		} catch (Exception e) {
			flag = false;
		}
		return flag;
	}

	/**
	 * 转换时间格式
	 * @param dateDate
	 * @return
	 */
	public static String dateToStr(Date dateDate) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
		String dateString = formatter.format(dateDate);
		return dateString;
	}
	/**
	 * 判断一个String 是否是数字
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("-?[0-9]*.?[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (isNum.matches()) {
			return true;
		}
		return false;
	}

	/**
	 * 得到时间（date）
	 * 
	 * @param intCount
	 *            1.8： 传8 位 yyyy-MM-dd; 2.14 传14 位 yyyy-MM-dd HH:mm:ss。
	 * @return Date
	 */
	public static Date getDateTime(int intCount) {
		Date dateTime = null;
		if (intCount == 8) {
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
			try {
				dateTime = df.parse(df.format(new Date()));
			} catch (ParseException e) {
				e.printStackTrace();
			}
			return dateTime;
		}
		if (intCount == 14) {
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
			try {
				dateTime = df.parse(df.format(new Date()));
			} catch (ParseException e) {
				e.printStackTrace();
			}
			return dateTime;
		}
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
		try {
			dateTime = df.parse(df.format(new Date()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return dateTime;
	}

	/**
	 * 得到时间（string）
	 * 
	 * @param intCount
	 *            1.8： 传8 位 yyyy-MM-dd; 2.14 传14 位 yyyy-MM-dd HH:mm:ss。
	 * @return String
	 */
	public static String getStrTime(int intCount) {
		String dateTime = null;
		if (intCount == 8) {
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
			dateTime = df.format(new Date());
			return dateTime;
		}
		if (intCount == 14) {
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
			dateTime = df.format(new Date());
			return dateTime;
		}
		if (intCount == 0) {
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd HHmmss");// 设置日期格式
			dateTime = df.format(new Date());
			return dateTime;
		}
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
		dateTime = df.format(new Date());
		return dateTime;
	}

	/**
	 * 生成 code
	 * 
	 * @param output
	 * @return
	 */
	public static String getAuthCodeImg(ByteArrayOutputStream output) {
		String code = "";
		for (int i = 0; i < 4; i++) {
			code += randomChar();
		}
		int width = 70;
		int height = 25;
		BufferedImage bi = new BufferedImage(width, height,
				BufferedImage.TYPE_3BYTE_BGR);
		Font font = new Font("Times New Roman", Font.PLAIN, 20);
		Graphics2D g = bi.createGraphics();
		g.setFont(font);
		Color color = new Color(66, 2, 82);
		g.setColor(color);
		g.setBackground(new Color(226, 226, 240));
		g.clearRect(0, 0, width, height);
		FontRenderContext context = g.getFontRenderContext();
		Rectangle2D bounds = font.getStringBounds(code, context);
		double x = (width - bounds.getWidth()) / 2;
		double y = (height - bounds.getHeight()) / 2;
		double ascent = bounds.getY();
		double baseY = y - ascent;
		g.drawString(code, (int) x, (int) baseY);
		g.dispose();
		try {
			ImageIO.write(bi, "jpg", output);
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("验证码:" + code);
		return code;
	}

	/**
	 * 验证码的参数
	 * 
	 * @return
	 */
	private static char randomChar() {
		Random r = new Random();
		String s = "ABCDEFGHIJKLMNOPQRSTUVWSYZ0123456789";
		return s.charAt(r.nextInt(s.length()));
	}

	/**
	 * 获取当前ipz地址
	 * 
	 * @return
	 */
	public static String getIp() {
		InetAddress address;
		String hostAddress = null;
		try {
			address = InetAddress.getLocalHost();
			hostAddress = address.getHostAddress();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}// 获取的是本地的IP地址 //PC-20140317PXKX/192.168.0.121
		return hostAddress;
	}

	/**
	 * $(document).ready(function() { changeCode();
	 * $("#getAuthCodeImg").bind("click", changeCode); }); function
	 * genTimestamp() { var time = new Date(); return time.getTime();
	 * 
	 * } function changeCode() { $("#getAuthCodeImg").attr("src",
	 * "indexGetAuthCode.do?t=" + genTimestamp()); }
	 */

	/**
	 * session 图形码
	 * 
	 * @param request
	 * @param response
	 *            code调用
	 * @RequestMapping(value="indexGetAuthCode.do") public void
	 *                                        indexGetAuthCode(HttpServletRequest
	 *                                        request,HttpServletResponse
	 *                                        response) { ByteArrayOutputStream
	 *                                        output = new
	 *                                        ByteArrayOutputStream(); String
	 *                                        code =
	 *                                        AllUtilMethod.getAuthCodeImg
	 *                                        (output);
	 *                                        CreateSessionUtil.indexSetAuthcode
	 *                                        (code); ServletOutputStream out
	 *                                        =null; try { out =
	 *                                        response.getOutputStream();
	 *                                        output.writeTo(out); out.close();
	 *                                        } catch (IOException e) {
	 *                                        e.printStackTrace(); } }
	 */

}
